use crate::utils::file_dir::{overwrite_file, read_all};

use super::{api::{get_latest, get_update}, cluster::CLUSTER, config::{DATA_PATH, VERSION}, file_content::FileContent};

pub async fn init_config_files() {
	let data_path = DATA_PATH.lock().unwrap();
	let version_path = format!("{}/version", data_path);
	let mut version = read_all(&version_path);
	if version.len() == 0 {
		// 如果本地不存在文件版本信息，就从服务器拉取最新的
		fetch_overwrite_all(&mut version, &version_path).await;
	} else {
		fetch_overwrite_update(&mut version, &version_path).await;
	}

	let mut g_version = VERSION.lock().unwrap();
	g_version.clear();
	g_version.push_str(&version);
}

pub async fn write_file_list(file_list: &Vec<FileContent>) {
	let cluster = CLUSTER.lock().unwrap();
	let prefix = &cluster.name;
	for file in file_list {
		if !file.name.starts_with(prefix.as_str()) {
			// not file in this cluster
			continue;
		}
		
		let root_idx = file.name.find('/');
		if root_idx.is_none() {
			// not a abs path str
			continue;
		}
		let root_idx = root_idx.unwrap();

		let path = &file.name[root_idx..file.name.len()];
		overwrite_file(&path.to_string(), &file.content).unwrap();
	}
}

pub async fn fetch_overwrite_all(version: &mut String, version_path: &String) {
	let latest_version = get_latest().await;
	write_file_list(&latest_version.file_content).await;
	version.clear();
	version.push_str(&latest_version.latest_version);
	// 将最新版本号写入文件（/etc/enderman/version）
	overwrite_file(version_path, &latest_version.latest_version).unwrap();
}

pub async fn fetch_overwrite_update(version: &mut String, version_path: &String) {
	let update = get_update(version).await;
	write_file_list(&update.update_content).await;
	version.clear();
	version.push_str(&update.latest_version);
	overwrite_file(version_path, &update.latest_version).unwrap();
}
